package reco.frame.demo.sample;


import reco.frame.demo.R;
import reco.frame.tv.remote.TvRemoteSocket;
import reco.frame.tv.remote.TvRemoteSocket.RemoteKeyListener;
import reco.frame.tv.remote.TvRemoteSocket.RemoteListener;
import reco.frame.tv.view.TvRelativeLayoutAsGroup;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

public class TvRemoteActivity extends Activity {
	private final static String TAG = "TvRemoteActivity";
	private ImageView iv_qr;
	private Handler handler = new Handler();
	private TvRelativeLayoutAsGroup trl_root;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_remote);
		
		trl_root = (TvRelativeLayoutAsGroup) findViewById(R.id.trl_root);

		iv_qr = (ImageView) findViewById(R.id.iv_qr);

		
		startRemoteKeyListener();
		startRemoteObserver();

	}
	
	private void startRemoteKeyListener(){
		TvRemoteSocket.instance(getApplicationContext()).setOnRemoteKeyListener(new RemoteKeyListener() {
			
			@Override
			public void onRemoteKeyDown(int keyCode) {
				Toast.makeText(getApplicationContext(), "keyCode="+keyCode, 0).show();
			}
		});
		
	}
	/**
	 * 四种示例 请求数据 发送数据 请求图片 发送图片
	 */
	private void startRemoteObserver() {
		TvRemoteSocket.instance(getApplicationContext()).setListener(
				new RemoteListener() {

					@Override
					public Object OnRemoteReceive(int action, final Object obj) {

						// 如欲进行主线程操作,请使用handler
						handler.post(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(getApplicationContext(),
										"收到请求=" + obj.toString(), 1).show();

							}
						});

						switch (action) {
						case CustomProtocol.ACTION_STRING:

							return "成功返回字符串";
						case CustomProtocol.ACTION_IMAGE_GET:

							// 此请求返回一张 bitmap格式图片
							return BitmapFactory.decodeResource(getResources(),
									R.drawable.eve);
						case CustomProtocol.ACTION_IMAGE_SEND:
							
							final Bitmap bmp=BitmapFactory.decodeFile(obj.toString());
							
							Log.e(TAG, obj.toString()+"---"+bmp);
							handler.post(new Runnable() {

								@Override
								public void run() {
									trl_root.setBackgroundDrawable(new BitmapDrawable(
											bmp));
								}
							});
							break;
						}

						return null;
					}

				});
		TvRemoteSocket.instance(getApplicationContext()).startRemoteServer(true);
	}

	/**
	 * 协议类
	 * 
	 * @author keYence
	 * 
	 */
	class CustomProtocol {
		public final static int ACTION_STRING = 0;
		public final static int ACTION_IMAGE_GET = 1;
		public final static int ACTION_IMAGE_SEND = 2;
	}
}
